package com.fishery.authority.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fishery.authority.entity.Role;
import com.fishery.authority.entity.RoleBase;
import com.fishery.authority.mapper.RoleBaseMapper;
import com.fishery.authority.service.RoleBaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fishery.authority.service.RoleService;
import com.fishery.entity.GlobalException;
import com.fishery.entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hy
 * @since 2021-03-08
 */
@Service
public class RoleBaseServiceImpl extends ServiceImpl<RoleBaseMapper, RoleBase> implements RoleBaseService {

    @Autowired
    private RoleService roleService;

    @Override
    public boolean baseCreateNewRole(RoleBase roleBase) {
        int insert = baseMapper.insert(roleBase);
        return insert == 1 ? true : false;
    }

    @Override
    public Map sliceListAchievePageSelectBaseDeRole(Integer start, Integer end, String baseId) {
        if (StringUtils.isEmpty(baseId)) {
            throw new GlobalException(Result.error("请输入正确的类型"));
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("base_id", baseId);
        List<RoleBase> roleBaseList = baseMapper.selectList(wrapper);
        //对start和end进行保护
        int size = roleBaseList.size();
        if(size == 0) {
            return null;
        }
        end = end > size ? size : end;
        List<Role> retList = new ArrayList<>();
        for(RoleBase roleBase : roleBaseList) {
            Role role = roleService.getById(roleBase.getRoleId());
            if(role != null) {
                retList.add(role);
            }
        }
        //切割
        List<Role> retListCopy = retList.subList(start, end);
        int ret_size = retList.size();
        Map<String, Object> map = new HashMap<>();
        map.put("retListCopy", retListCopy);
        map.put("totla", ret_size);
        return map;
    }

    @Override
    public List<Role> SelectBaseDeRole(String baseId) {
        if (StringUtils.isEmpty(baseId)) {
            throw new GlobalException(Result.error("请输入正确的类型"));
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("base_id", baseId);
        List<RoleBase> roleBaseList = baseMapper.selectList(wrapper);
        //对start和end进行保护
        List<Role> retList = new ArrayList<>();
        for(RoleBase roleBase : roleBaseList) {
            Role role = roleService.getById(roleBase.getRoleId());
            if(role != null) {
                retList.add(role);
            }
        }
        return retList;
    }

}
